package com.danhuang.cloud.danhuanguser.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.danhuang.cloud.danhuangcore.constant.ResConstant;
import com.danhuang.cloud.danhuangcore.entity.UserInfoDTO;
import com.danhuang.cloud.danhuangcore.model.DhRes;
import com.danhuang.cloud.danhuangcore.model.DhUserInfo;
import com.danhuang.cloud.danhuanguser.mapper.UserMapper;
import com.danhuang.cloud.danhuanguser.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public DhRes searchOpenId(String openId) {
        try {
            DhUserInfo dhUserInfo = userMapper.selectById(openId);
            if(dhUserInfo != null){
                return DhRes.success(dhUserInfo);
            }

            return DhRes.fail(ResConstant.NO_RESULT_CODE, dhUserInfo);
        }catch (Exception e){
            log.error("查询用户异常",e);
            return DhRes.fail(ResConstant.SYSTEM_ERROR_CODE);
        }
    }

    @Override
    public DhRes createUser(UserInfoDTO userInfoDTO) {
        try {
            DhRes r = this.searchOpenId(userInfoDTO.getOpenId());

           if(ResConstant.SUCCESS_CODE.equals(r.getCode())){
               return r;
           }

            DhUserInfo dhUserInfo = new DhUserInfo();
            BeanUtil.copyProperties( userInfoDTO, dhUserInfo);

            dhUserInfo.setCreateTime(new Date());

            if(dhUserInfo != null){
                userMapper.insert(dhUserInfo);
            }

            DhUserInfo user = userMapper.selectById(userInfoDTO.getOpenId());

            return DhRes.success(user);
        }catch (Exception e){
            log.error("创建用户异常",e);
            return DhRes.fail(ResConstant.SYSTEM_ERROR_CODE);
        }
    }
}
